package com.css.zfzx.fxpg.modules.middle.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.fxpg.common.utils.BeanUtil;
import com.css.zfzx.fxpg.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.fxpg.modules.middle.repository.FxMiddleResultNativeRepository;
import com.css.zfzx.fxpg.modules.middle.repository.FxMiddleResultRepository;
import com.css.zfzx.fxpg.modules.middle.repository.entity.FxMiddleResultEntity;
import com.css.zfzx.fxpg.modules.middle.service.FxMiddleResultService;
import com.css.zfzx.fxpg.modules.middle.viewobjects.FxMiddleResultQueryParams;
import com.css.zfzx.fxpg.modules.middle.viewobjects.FxMiddleResultVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.PageImpl;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author andy
 * @date 2020-11-12
 */
@Service
@Slf4j
public class FxMiddleResultServiceImpl implements FxMiddleResultService {

	@Autowired
    private FxMiddleResultRepository fxMiddleResultRepository;
    @Autowired
    private FxMiddleResultNativeRepository fxMiddleResultNativeRepository;

    @Override
    public JSONObject queryFxMiddleResults(FxMiddleResultQueryParams queryParams, int curPage, int pageSize) {
        Page<FxMiddleResultEntity> fxMiddleResultPage = this.fxMiddleResultNativeRepository.queryFxMiddleResults(queryParams, curPage, pageSize);
        List<FxMiddleResultVO> fxMiddleResultVOList = new ArrayList<>();
        List<FxMiddleResultEntity> fxMiddleResultEntityList = fxMiddleResultPage.getContent();
        for(FxMiddleResultEntity fxMiddleResultEntity : fxMiddleResultEntityList){
            FxMiddleResultVO fxMiddleResultVO = new FxMiddleResultVO();
            BeanUtils.copyProperties(fxMiddleResultEntity, fxMiddleResultVO);
            if(PlatformObjectUtils.isNotEmpty(fxMiddleResultEntity.getEarthquakeIntensity())) {
                fxMiddleResultVO.setEarthquakeIntensityName(findByDictCodeAndDictItemCode("earthquakeIntensity", fxMiddleResultEntity.getEarthquakeIntensity()));
            }
            if(PlatformObjectUtils.isNotEmpty(fxMiddleResultEntity.getDamageDegree())) {
                fxMiddleResultVO.setDamageDegreeName(findByDictCodeAndDictItemCode("damageDegree", fxMiddleResultEntity.getDamageDegree()));
            }
            fxMiddleResultVOList.add(fxMiddleResultVO);
        }
        Page<FxMiddleResultVO> FxMiddleResultVOPage = new PageImpl(fxMiddleResultVOList, fxMiddleResultPage.getPageable(), fxMiddleResultPage.getTotalElements());
        JSONObject jsonObject = PlatformPageUtils.formatPageData(FxMiddleResultVOPage);
        return jsonObject;
    }


    @Override
    public FxMiddleResultEntity getFxMiddleResult(String id) {
        FxMiddleResultEntity fxMiddleResult = this.fxMiddleResultRepository.findById(id).orElse(null);
         return fxMiddleResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxMiddleResultEntity saveFxMiddleResult(FxMiddleResultEntity fxMiddleResult) {
        String uuid = UUIDGenerator.getUUID();
        fxMiddleResult.setId(uuid);
        fxMiddleResult.setCreateUser(PlatformSessionUtils.getUserId());
        fxMiddleResult.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        this.fxMiddleResultRepository.save(fxMiddleResult);
        return fxMiddleResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FxMiddleResultEntity updateFxMiddleResult(FxMiddleResultEntity fxMiddleResult) {
        fxMiddleResult.setUpdateUser(PlatformSessionUtils.getUserId());
        fxMiddleResult.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = fxMiddleResult.getId();
        FxMiddleResultEntity one = fxMiddleResultRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(fxMiddleResult, one);
        this.fxMiddleResultRepository.save(one);
        return fxMiddleResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteFxMiddleResults(List<String> ids) {
        List<FxMiddleResultEntity> fxMiddleResultList = this.fxMiddleResultRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(fxMiddleResultList) && fxMiddleResultList.size() > 0) {
            for(FxMiddleResultEntity fxMiddleResult : fxMiddleResultList) {
                this.fxMiddleResultRepository.delete(fxMiddleResult);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public String findByDictCodeAndDictItemCode(String dictCode, String dictItemCode){
        DictItemEntity dictItem = PlatformAPI.getDictAPI().getValidDictItemByDictCodeAndDictItemCode(dictCode, dictItemCode);
        String dictItemName = "";
        if(PlatformObjectUtils.isNotEmpty(dictItem)){
            dictItemName = dictItem.getDictItemName();
        }
        return dictItemName;
    }

    @Override
    public String exportExcel(FxMiddleResultQueryParams queryParams, HttpServletResponse response) {
        try {
            List<FxMiddleResultEntity> middleEntities = fxMiddleResultNativeRepository.listFxMiddleResultss(queryParams);
            // 深拷贝
            ArrayList<FxMiddleResultVO> vos = new ArrayList<>();
            for (FxMiddleResultEntity middleEntity : middleEntities) {
                FxMiddleResultVO vo = new FxMiddleResultVO();
                BeanUtils.copyProperties(middleEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "中间结果数据统计", "中间结果数据", FxMiddleResultVO.class, "中间结果信息数据.xlsx", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    @Override
    public List<FxMiddleResultEntity> queryFxMiddleResults(FxMiddleResultQueryParams queryParams) {
        List<FxMiddleResultEntity> fxMiddleResults = this.fxMiddleResultNativeRepository.listFxMiddleResultss(queryParams);
        return fxMiddleResults;
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置解析从第1+1+1行开始
            params.setTitleRows(1);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<FxMiddleResultVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), FxMiddleResultVO.class, params);
            List<FxMiddleResultVO> list = result.getList();
            // 批量新增
            this.saveData(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<FxMiddleResultVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    FxMiddleResultVO middleResultVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + middleResultVO.getRowNum() + "行" + middleResultVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (RuntimeException e) {
            log.error(e.getMessage(), e);
            return e.getMessage();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            if ("库中该数据最多一条，请管理员清理数据库冗余数据！".equals(e.getMessage())) {
                return e.getMessage();
            } else {
                return "导入失败，请检查数据正确性";
            }
        }
    }

    private void saveData(List<FxMiddleResultVO> list) {
        for (int i = 0; i < list.size(); i++) {
            FxMiddleResultEntity middleResultEntity = new FxMiddleResultEntity();
            FxMiddleResultVO middleResultVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(middleResultVO, middleResultEntity);
            middleResultEntity.setIsValid("1");
            saveOrUpdate(middleResultEntity);
        }
    }

    /**
     * 保存或者修改（OBJECTID字段值相同的数据只能有一条数据）
     *
     * @param middleResultEntity
     */
    @Override
    public void saveOrUpdate(FxMiddleResultEntity middleResultEntity) {
        FxMiddleResultQueryParams queryParams = new FxMiddleResultQueryParams();
        queryParams.setProvince(middleResultEntity.getProvince());
        queryParams.setCity(middleResultEntity.getCity());
        queryParams.setArea(middleResultEntity.getArea());
        queryParams.setEarthquakeIntensity(middleResultEntity.getEarthquakeIntensity());
        queryParams.setDamageDegree(middleResultEntity.getDamageDegree());
        List<FxMiddleResultEntity> middleResultEntities = fxMiddleResultNativeRepository.listFxMiddleResultss(queryParams);
        // 若查到数据为空，则新增
        if (CollectionUtils.isEmpty(middleResultEntities)) {
            this.saveFxMiddleResult(middleResultEntity);
        } else {
            if (middleResultEntities.size() == 1) {
                FxMiddleResultEntity sourceProvinceEntity = middleResultEntities.get(0);
                BeanUtil.copyPropertiesIgnoreNull(middleResultEntity, sourceProvinceEntity);
                this.updateFxMiddleResult(sourceProvinceEntity);
            } else {
                throw new RuntimeException("库中该数据最多一条，请管理员清理数据库冗余数据！");
            }
        }
    }

}
